# -*- coding: iso-8859-1 -*-
#
#    This is part of Malvinas Argentinas Messenger
#
#    Malvinas Argentinas Messenger is free software; you can redistribute
#    it and/or modify it under the terms of the GNU General Public License
#    as published by the Free Software Foundation; either version 2 of the
#    License, or (at your option) any later version.
#
#    Malvinas Argentinas Messenger is distributed in the hope that it will be
#    useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Malvinas Argentinas Messenger; if not, write to the Free
#    Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
#    MA  02110-1301  USA

import string
import random
import msnlib, msnp2p
import base64


SEND_ACCEPT = 'MIME-Version: 1.0\r\nContent-Type: text/x-msmsgsinvite; charset=UTF-8\r\n\r\nInvitation-Command: ACCEPT\r\nInvitation-Cookie: %d\r\nLaunch-Application: FALSE\r\nRequest-Data: IP-Address:\r\n\r\n'
SEND_REJECT = 'MIME-Version: 1.0\r\nContent-Type: text/x-msmsgsinvite; charset=UTF-8\r\n\r\nInvitation-Command: CANCEL\r\nInvitation-Cookie: %d\r\nCancel-Code: REJECT\r\n\r\n'
DOWNLOAD_DIR = '/home/andres'

class FileRecv(Comm):
	def __init__(self, session, chat, user, cookie, fileName, size):
		#Comm.__init__(self)
		self.user = user
		self.session = session
		self.chat = chat
		self.cookie = cookie
		self.fileName = fileName
		self.size = size
		self.file = None
		self.received = 0
		self.state = 'RECV_CREATED'
		self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

	def init(self, authCookie, host, port):
		self.authCookie = authCookie
		self.host = host
		self.port = port

		try:
			self.file = open(DOWNLOAD_DIR + self.fileName, 'w')
		except IOError, e:
			self.session.pError( e[1] )

		self.ready = 1
		self.session.addConnectingFileRecv(self)

	def accept(self):
		msg = SEND_ACCEPT % (self.cookie)
		nBytes = len(msg)
		self.chat.send('MSG', 'N %d\r\n%s' % (nBytes, msg))
		self.state = 'RECV_ACCEPTED'

	def reject(self):
		msg = SEND_REJECT % (self.cookie)
		nBytes = len(msg)
		self.chat.send('MSG', 'N %d\r\n%s' % (nBytes, msg))
		self.session.removeFileRecv(self)

	def recvChunk(self, chunk):
		size1 = ord(chunk[1])
		size2 = ord(chunk[2])
		self.received = self.received + (size1 + size2*256)
		self.pDebug('size1= %d, size2= %d' % (size1, size2))
		self.file.write(chunk[3:])
	
	def close(self):
		self.sendRaw('BYE 16777989\r\n')
		self.s.close()
		self.file.close()
